package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

//将redis中的推荐动态数据,保存到mongodb中
@Component
public class MovementJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 * * * * ?")
    public void recommend() {
        System.out.println("同步开始");
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                Long userId = Long.parseLong(key.replaceAll("QUANZI_PUBLISH_RECOMMEND_", ""));//推荐给谁
                String pidArrStr = stringRedisTemplate.opsForValue().get(key);
                String[] pidArr = pidArrStr.split(",");
                for (String pid : pidArr) {
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);

                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setUserId(userId);
                    recommendMovement.setPid(Long.parseLong(pid));
                    recommendMovement.setPublishId(movement.getId());
                    recommendMovement.setScore(RandomUtil.randomDouble(90,100));

                    mongoTemplate.save(recommendMovement);
                }

                //删除
                stringRedisTemplate.delete(key);
            }
        }
        System.out.println("同步结束");

    }

}
